package com.styletransfer.service;

import com.styletransfer.exception.BusinessException;
import com.styletransfer.mapper.CombinationDetailMapper;
import com.styletransfer.mapper.CombinationMapper;
import com.styletransfer.mapper.StyleMapper;
import com.styletransfer.mapper.WorkMapper;
import com.styletransfer.mapper.FavoriteMapper;
import com.styletransfer.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 组合服务类
 *
 * 这个类负责处理与风格组合相关的业务逻辑，包括组合的创建、更新、查询等。
 * 风格组合是多个风格按照不同权重混合在一起，可以创造出更丰富的效果。
 */
@Service
public class CombinationService {

    @Autowired
    private CombinationMapper combinationMapper;

    @Autowired
    private CombinationDetailMapper combinationDetailMapper;

    @Autowired
    private StyleMapper styleMapper;

    @Autowired
    private OssService ossService;

    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private FavoriteMapper favoriteMapper;

    /**
     * 创建组合
     *
     * @param combination 组合对象
     * @param previewImage 预览图片
     * @param details 组合详情列表
     * @return API响应
     */
    @Transactional
    public ApiResponse<Combination> createCombination(Combination combination, MultipartFile previewImage, List<CombinationDetail> details) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();
        combination.setCreatorId(userId);

        // 上传预览图片
        if (previewImage != null && !previewImage.isEmpty()) {
            String previewImagePath = ossService.uploadFile(previewImage, "combinations");
            combination.setPreviewImage(previewImagePath);
        } else {
            throw new BusinessException("预览图片不能为空");
        }

        // 检查组合详情
        if (details == null || details.isEmpty()) {
            throw new BusinessException("组合详情不能为空");
        }

        // 检查组合中的风格是否存在
        for (CombinationDetail detail : details) {
            if (styleMapper.findById(detail.getStyleId()) == null) {
                throw new BusinessException("风格不存在：" + detail.getStyleId());
            }
        }

        // 设置默认值
        combination.setUseCount(0);
        combination.setLikeCount(0);
        combination.setFavoriteCount(0);
        combination.setCreateTime(new Date());
        combination.setUpdateTime(new Date());
        combination.setStatus(1); // 1:正常, 0:删除

        // 如果没有设置是否公开，默认为公开
        if (combination.getIsPublic() == null) {
            combination.setIsPublic(1); // 1:公开, 0:私有
        }

        // 插入组合
        combinationMapper.insert(combination);

        // 插入组合详情
        for (CombinationDetail detail : details) {
            detail.setCombinationId(combination.getId());
            detail.setCreateTime(new Date());
            detail.setUpdateTime(new Date());
            combinationDetailMapper.insert(detail);
        }

        return ApiResponse.success(combination);
    }

    /**
     * 更新组合
     *
     * @param combination 组合对象
     * @param previewImage 预览图片
     * @param details 组合详情列表
     * @return API响应
     */
    @Transactional
    public ApiResponse<Combination> updateCombination(Combination combination, MultipartFile previewImage, List<CombinationDetail> details) {
        // 检查组合是否存在
        Combination existingCombination = combinationMapper.findById(combination.getId());
        if (existingCombination == null) {
            throw new BusinessException("组合不存在");
        }

        // 检查是否有权限修改
        if (!isAdmin() && !existingCombination.getCreatorId().equals(getCurrentUserId())) {
            throw new BusinessException("没有权限修改此组合");
        }

        // 上传预览图片
        if (previewImage != null && !previewImage.isEmpty()) {
            // 删除旧图片
            if (existingCombination.getPreviewImage() != null && !existingCombination.getPreviewImage().isEmpty()) {
                ossService.deleteFile(existingCombination.getPreviewImage());
            }

            // 上传新图片
            String previewImagePath = ossService.uploadFile(previewImage, "combinations");
            combination.setPreviewImage(previewImagePath);
        } else {
            // 保持原图片
            combination.setPreviewImage(existingCombination.getPreviewImage());
        }

        // 检查组合详情
        if (details != null && !details.isEmpty()) {
            // 检查组合中的风格是否存在
            for (CombinationDetail detail : details) {
                if (styleMapper.findById(detail.getStyleId()) == null) {
                    throw new BusinessException("风格不存在：" + detail.getStyleId());
                }
            }
        }

        // 设置不可修改的字段
        combination.setCreatorId(existingCombination.getCreatorId());
        combination.setUseCount(existingCombination.getUseCount());
        combination.setLikeCount(existingCombination.getLikeCount());
        combination.setFavoriteCount(existingCombination.getFavoriteCount());
        combination.setCreateTime(existingCombination.getCreateTime());
        combination.setStatus(existingCombination.getStatus());
        combination.setUpdateTime(new Date());

        // 更新组合
        combinationMapper.update(combination);

        // 更新组合详情
        if (details != null && !details.isEmpty()) {
            // 删除所有旧的组合详情
            combinationDetailMapper.deleteByCombination(combination.getId());

            // 插入新的组合详情
            for (CombinationDetail detail : details) {
                detail.setCombinationId(combination.getId());
                detail.setCreateTime(new Date());
                detail.setUpdateTime(new Date());
                combinationDetailMapper.insert(detail);
            }
        }

        return ApiResponse.success(combination);
    }

    /**
     * 删除组合
     *
     * @param id 组合ID
     * @return API响应
     */
    @Transactional
    public ApiResponse<Void> deleteCombination(Long id) {
        // 检查组合是否存在
        Combination combination = combinationMapper.findById(id);
        if (combination == null) {
            throw new BusinessException("组合不存在");
        }

        // 检查是否有权限删除
        if (!isAdmin() && !combination.getCreatorId().equals(getCurrentUserId())) {
            throw new BusinessException("没有权限删除此组合");
        }

        // 删除图片
        if (combination.getPreviewImage() != null && !combination.getPreviewImage().isEmpty()) {
            ossService.deleteFile(combination.getPreviewImage());
        }

        // 删除组合详情
        combinationDetailMapper.deleteByCombination(id);

        // 更新组合状态为已删除
        combinationMapper.updateStatus(id, 0);

        return ApiResponse.success();
    }

    /**
     * 根据ID查询组合
     *
     * @param id 组合ID
     * @return API响应
     */
    public ApiResponse<Combination> findById(Long id) {
        Combination combination = combinationMapper.findById(id);
        if (combination == null) {
            throw new BusinessException("组合不存在");
        }
        ArrayList<Long> styleIds = new ArrayList<>();
        List<CombinationDetail> details = combinationDetailMapper.findByCombination(id);
        for (CombinationDetail detail : details) {
            styleIds.add(detail.getStyleId());
        }
        combination.setStyleIds(styleIds);
        return ApiResponse.success(combination);
    }

    /**
     * 查询组合详情
     *
     * @param combinationId 组合ID
     * @return API响应
     */
    public ApiResponse<List<CombinationDetail>> findDetails(Long combinationId) {
        // 检查组合是否存在
        Combination combination = combinationMapper.findById(combinationId);
        if (combination == null) {
            throw new BusinessException("组合不存在");
        }

        // 查询组合详情
        List<CombinationDetail> details = combinationDetailMapper.findByCombination(combinationId);

        return ApiResponse.success(details);
    }

    /**
     * 查询用户的组合
     *
     * @param userId 用户ID
     * @return API响应
     */
    public ApiResponse<List<Combination>> findByUser(Long userId) {
        List<Combination> combinations = combinationMapper.findByUser(userId);
        return ApiResponse.success(combinations);
    }

    /**
     * 查询公开的组合
     *
     * @return API响应
     */
    public ApiResponse<List<Combination>> findPublic() {
        List<Combination> combinations = combinationMapper.findPublic();

        // 为每个组合添加styleIds字段
        for (Combination combination : combinations) {
            List<CombinationDetail> details = combinationDetailMapper.findByCombination(combination.getId());
            List<Long> styleIds = details.stream()
                    .map(CombinationDetail::getStyleId)
                    .collect(Collectors.toList());
            combination.setStyleIds(styleIds);
        }

        return ApiResponse.success(combinations);
    }

    /**
     * 查询热门组合
     *
     * @param limit 限制数
     * @return API响应
     */
    public ApiResponse<List<Combination>> findHot(Integer limit) {
        List<Combination> combinations = combinationMapper.findHot(limit);

        // 为每个组合添加styleIds字段
        for (Combination combination : combinations) {
            List<CombinationDetail> details = combinationDetailMapper.findByCombination(combination.getId());
            List<Long> styleIds = details.stream()
                    .map(CombinationDetail::getStyleId)
                    .collect(Collectors.toList());
            combination.setStyleIds(styleIds);
        }

        return ApiResponse.success(combinations);
    }

    /**
     * 查询最新组合
     *
     * @param limit 限制数
     * @return API响应
     */
    public ApiResponse<List<Combination>> findLatest(Integer limit) {
        List<Combination> combinations = combinationMapper.findLatest(limit);

        // 为每个组合添加styleIds字段
        for (Combination combination : combinations) {
            List<CombinationDetail> details = combinationDetailMapper.findByCombination(combination.getId());
            List<Long> styleIds = details.stream()
                    .map(CombinationDetail::getStyleId)
                    .collect(Collectors.toList());
            combination.setStyleIds(styleIds);
        }

        return ApiResponse.success(combinations);
    }

    /**
     * 搜索组合
     *
     * @param keyword 关键词
     * @return API响应
     */
    public ApiResponse<List<Combination>> search(String keyword) {
        List<Combination> combinations = combinationMapper.search(keyword);
        return ApiResponse.success(combinations);
    }

    /**
     * 分页查询组合
     *
     * @param pageRequest 分页请求
     * @return 分页响应
     */
    public PageResponse<Combination> findByPage(PageRequest pageRequest) {
        // 计算偏移量
        Integer offset = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();

        // 查询数据
        List<Combination> combinations = combinationMapper.findByPage(offset, pageRequest.getPageSize());
        Long total = combinationMapper.count();

        // 构建分页响应
        return new PageResponse<>(combinations, total, pageRequest.getPageNum(), pageRequest.getPageSize());
    }

    /**
     * 增加组合使用次数
     *
     * @param id 组合ID
     * @return API响应
     */
    public ApiResponse<Void> incrementUseCount(Long id) {
        // 检查组合是否存在
        Combination combination = combinationMapper.findById(id);
        if (combination == null) {
            throw new BusinessException("组合不存在");
        }

        // 增加使用次数
        combinationMapper.incrementUseCount(id);

        return ApiResponse.success();
    }

    /**
     * 创建风格组合生成任务
     *
     * @param imageUrl 原图URL
     * @param styleIds 风格ID数组
     * @param intensity 风格强度
     * @return API响应，包含任务ID
     */
    public ApiResponse<Object> createStyleTask(String imageUrl, List<Long> styleIds, Integer intensity) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();

        // 参数校验
        if (imageUrl == null || imageUrl.isEmpty()) {
            return ApiResponse.error("图片URL不能为空");
        }

        if (styleIds == null || styleIds.isEmpty()) {
            return ApiResponse.error("至少需要选择一种风格");
        }

        if (intensity == null || intensity < 0 || intensity > 100) {
            intensity = 100; // 默认强度为100
        }

        try {
            // 创建任务
            String taskId = generateTaskId();

            // 在实际项目中，这里应该将任务信息保存到数据库，并启动异步任务进行风格转换处理
            // 这里简化处理，直接返回任务ID

            // 返回任务ID
            return ApiResponse.success(new TaskResponse(taskId));
        } catch (Exception e) {
            return ApiResponse.error("创建任务失败: " + e.getMessage());
        }
    }

    /**
     * 生成任务ID
     *
     * @return 任务ID
     */
    private String generateTaskId() {
        // 简单实现，使用时间戳和随机数生成任务ID
        return "task_" + System.currentTimeMillis() + "_" + (int)(Math.random() * 1000);
    }

    /**
     * 获取当前用户ID
     *
     * @return 用户ID
     */
    private Long getCurrentUserId() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Object principal = authentication.getPrincipal();

            // 从自定义UserDetails中获取用户ID
            if (principal instanceof com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) {
                return ((com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) principal).getUserId();
            }

            // 尝试从请求属性中获取用户ID
            javax.servlet.http.HttpServletRequest request =
                    ((org.springframework.web.context.request.ServletRequestAttributes)
                            org.springframework.web.context.request.RequestContextHolder.getRequestAttributes()).getRequest();
            Object userId = request.getAttribute("userId");
            if (userId != null) {
                return (Long) userId;
            }

            throw new RuntimeException("无法获取用户ID");
        } catch (Exception e) {
            throw new RuntimeException("获取用户ID失败: " + e.getMessage());
        }
    }

    /**
     * 检查当前用户是否为管理员
     *
     * @return 是否为管理员
     */
    private boolean isAdmin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getAuthorities().stream()
                .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
    }

    /**
     * 获取组合相关作品
     *
     * @param combinationId 组合ID
     * @param pageRequest 分页请求
     * @return API响应
     */
    public ApiResponse<PageResponse<Work>> getCombinationWorks(Long combinationId, PageRequest pageRequest) {
        // 检查组合是否存在
        Combination combination = combinationMapper.findById(combinationId);
        if (combination == null) {
            throw new BusinessException("组合不存在");
        }

        // 获取组合详情，提取风格ID
        List<CombinationDetail> details = combinationDetailMapper.findByCombination(combinationId);
        if (details.isEmpty()) {
            return ApiResponse.success(new PageResponse<>(Collections.emptyList(), 0L, pageRequest.getPageNum(), pageRequest.getPageSize()));
        }

        // 从组合详情中提取风格ID列表
        List<Long> styleIds = details.stream()
                .map(CombinationDetail::getStyleId)
                .collect(Collectors.toList());

        // 计算分页参数
        Integer offset = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();
        Integer limit = pageRequest.getPageSize();

        // 查询使用了这些风格的作品
        // 注意：这里简化处理，只查询使用了其中任一风格的作品
        // 实际项目中可能需要更复杂的查询逻辑
        List<Work> works = workMapper.findByStylesPage(styleIds, offset, limit);
        Long total = workMapper.countByStyles(styleIds);

        // 构建分页响应
        PageResponse<Work> pageResponse = new PageResponse<>(works, total, pageRequest.getPageNum(), pageRequest.getPageSize());
        return ApiResponse.success(pageResponse);
    }

    /**
     * 获取组合示例
     *
     * @param combinationId 组合ID
     * @return API响应
     */
    public ApiResponse<List<Work>> getCombinationExamples(Long combinationId) {
        // 检查组合是否存在
        Combination combination = combinationMapper.findById(combinationId);
        if (combination == null) {
            throw new BusinessException("组合不存在");
        }

        // 获取组合详情，提取风格ID
        List<CombinationDetail> details = combinationDetailMapper.findByCombination(combinationId);
        if (details.isEmpty()) {
            return ApiResponse.success(Collections.emptyList());
        }

        // 从组合详情中提取风格ID列表
        List<Long> styleIds = details.stream()
                .map(CombinationDetail::getStyleId)
                .collect(Collectors.toList());

        // 查询使用了这些风格的热门作品作为示例
        // 限制返回5个作品
        List<Work> examples = workMapper.findByStylesHot(styleIds, 5);
        return ApiResponse.success(examples);
    }

    /**
     * 检查组合是否已收藏
     *
     * @param combinationId 组合ID
     * @return API响应
     */
    public ApiResponse<Boolean> checkFavoriteCombination(Long combinationId) {
        // 检查组合是否存在
        Combination combination = combinationMapper.findById(combinationId);
        if (combination == null) {
            throw new BusinessException("组合不存在");
        }

        // 获取当前登录用户ID
        Long userId = getCurrentUserId();

        // 查询是否已收藏
        Favorite favorite = favoriteMapper.findByUserAndTarget(userId, combinationId, 2); // 2表示组合类型
        return ApiResponse.success(favorite != null);
    }

    /**
     * 收藏/取消收藏组合
     *
     * @param combinationId 组合ID
     * @param isFavorite 是否收藏
     * @return API响应
     */
    @Transactional
    public ApiResponse<Void> toggleFavoriteCombination(Long combinationId, Boolean isFavorite) {
        // 检查组合是否存在
        Combination combination = combinationMapper.findById(combinationId);
        if (combination == null) {
            throw new BusinessException("组合不存在");
        }

        // 获取当前登录用户ID
        Long userId = getCurrentUserId();

        // 查询是否已收藏
        Favorite favorite = favoriteMapper.findByUserAndTarget(userId, combinationId, 2); // 2表示组合类型

        if (isFavorite) {
            // 收藏操作
            if (favorite == null) {
                // 创建新收藏
                Favorite newFavorite = new Favorite();
                newFavorite.setUserId(userId);
                newFavorite.setTargetId(combinationId);
                newFavorite.setType(2); // 2表示组合类型
                newFavorite.setCreateTime(new Date());
                favoriteMapper.insert(newFavorite);

                // 更新组合收藏数
                combinationMapper.incrementFavoriteCount(combinationId);
            }
        } else {
            // 取消收藏操作
            if (favorite != null) {
                // 删除收藏
                favoriteMapper.delete(favorite.getId());

                // 更新组合收藏数
                combinationMapper.decrementFavoriteCount(combinationId);
            }
        }

        return ApiResponse.success();
    }

    /**
     * 获取组合相关风格
     *
     * @param combinationId 组合ID
     * @return API响应
     */
    public ApiResponse<List<Style>> getCombinationStyles(Long combinationId) {
        // 检查组合是否存在
        Combination combination = combinationMapper.findById(combinationId);
        if (combination == null) {
            throw new BusinessException("组合不存在");
        }

        // 获取组合详情，提取风格ID
        List<CombinationDetail> details = combinationDetailMapper.findByCombination(combinationId);
        if (details.isEmpty()) {
            return ApiResponse.success(Collections.emptyList());
        }

        // 从组合详情中提取风格ID列表
        List<Long> styleIds = details.stream()
                .map(CombinationDetail::getStyleId)
                .collect(Collectors.toList());

        // 查询风格详情
        List<Style> styles = new ArrayList<>();
        for (Long styleId : styleIds) {
            Style style = styleMapper.findById(styleId);
            if (style != null) {
                styles.add(style);
            }
        }

        return ApiResponse.success(styles);
    }

    /**
     * 创建风格组合（JSON格式请求）
     *
     * @return API响应
     */
    @Transactional
    public ApiResponse<Map<String, Object>> createCombination(StyleTaskRequest request) {
        Integer intensity = request.getIntensity();
        String name = request.getName();
        String description = request.getDescription();
        Integer isPublic = request.getIsPublic();
        String imageUrl = request.getImageUrl();
        List<Long> styleIds = request.getStyleIds();
        // 参数校验
        if (imageUrl == null || imageUrl.isEmpty()) {
            return ApiResponse.error("图片URL不能为空");
        }

        if (styleIds == null || styleIds.isEmpty()) {
            return ApiResponse.error("至少需要选择一种风格");
        }

        if (intensity == null || intensity < 0 || intensity > 100) {
            intensity = 50; // 默认强度为50
        }

        // 获取当前登录用户ID
        Long userId = getCurrentUserId();

        // 创建组合对象
        Combination combination = new Combination();
        combination.setCreatorId(userId);
        combination.setPreviewImage(imageUrl);
        combination.setCoverImage(imageUrl);
        combination.setName(name);
        combination.setDescription(description);
        combination.setUseCount(0);
        combination.setLikeCount(0);
        combination.setFavoriteCount(0);
        combination.setCreateTime(new Date());
        combination.setUpdateTime(new Date());
        combination.setStatus(1); // 1:正常, 0:删除
        combination.setIsPublic(isPublic); // 1:公开, 0:私有

        // 插入组合
        combinationMapper.insert(combination);

        // 创建组合详情
        int order = 1;
        for (Long styleId : styleIds) {
            // 检查风格是否存在
            if (styleMapper.findById(styleId) == null) {
                return ApiResponse.error("风格不存在：" + styleId);
            }

            // 创建组合详情
            CombinationDetail detail = new CombinationDetail();
            detail.setCombinationId(combination.getId());
            detail.setStyleId(styleId);
            detail.setWeight(1.0); // 默认权重为1
            detail.setDisplayOrder(order++);
            detail.setCreateTime(new Date());
            detail.setUpdateTime(new Date());

            // 插入组合详情
            combinationDetailMapper.insert(detail);
        }

        // 返回组合ID
        Map<String, Object> result = new HashMap<>();
        result.put("combinationId", combination.getId());
        return ApiResponse.success(result);
    }

    /**
     * 更新风格组合（JSON格式请求）
     *
     * @param id 组合ID
     * @param imageUrl 图片URL
     * @param styleIds 风格ID列表
     * @param intensity 风格强度
     * @return API响应
     */
    @Transactional
    public ApiResponse<Map<String, Object>> updateCombination(Long id, String imageUrl, List<Long> styleIds, Integer intensity) {
        // 参数校验
        if (id == null) {
            return ApiResponse.error("组合ID不能为空");
        }

        if (imageUrl == null || imageUrl.isEmpty()) {
            return ApiResponse.error("图片URL不能为空");
        }

        if (styleIds == null || styleIds.isEmpty()) {
            return ApiResponse.error("至少需要选择一种风格");
        }

        if (intensity == null || intensity < 0 || intensity > 100) {
            intensity = 50; // 默认强度为50
        }

        // 查询组合是否存在
        Combination existingCombination = combinationMapper.findById(id);
        if (existingCombination == null) {
            return ApiResponse.error("组合不存在");
        }

        // 检查是否有权限修改
        Long userId = getCurrentUserId();
        if (!isAdmin() && !existingCombination.getCreatorId().equals(userId)) {
            return ApiResponse.error("没有权限修改此组合");
        }

        // 更新组合信息
        existingCombination.setPreviewImage(imageUrl);
        existingCombination.setUpdateTime(new Date());

        // 更新组合
        combinationMapper.update(existingCombination);

        // 删除原有组合详情
        combinationDetailMapper.deleteByCombination(id);

        // 创建新的组合详情
        int order = 1;
        for (Long styleId : styleIds) {
            // 检查风格是否存在
            if (styleMapper.findById(styleId) == null) {
                return ApiResponse.error("风格不存在：" + styleId);
            }

            // 创建组合详情
            CombinationDetail detail = new CombinationDetail();
            detail.setCombinationId(id);
            detail.setStyleId(styleId);
            detail.setWeight(1.0); // 默认权重为1
            detail.setDisplayOrder(order++);
            detail.setCreateTime(new Date());
            detail.setUpdateTime(new Date());

            // 插入组合详情
            combinationDetailMapper.insert(detail);
        }

        // 返回组合ID
        Map<String, Object> result = new HashMap<>();
        result.put("combinationId", id);
        return ApiResponse.success(result);
    }
}

class TaskResponse {
    private String taskId;

    public TaskResponse(String taskId) {
        this.taskId = taskId;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }
}
